<?php
/**
 * @version $Id: unocart.class.php 21 2010-05-14 13:24:08Z vladzimirs $
 * @package UnoCart
 * @copyright Авторские права (C) 2009-2010 UnoCart team & (C) 2007-2010 Joostina team &. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * UnoCart! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл help/copyright.php.
 */
defined('_VALID_MOS') or die('Restricted access');
class unocartCategory extends mosDBTable
{
    var $category_id = null;
    var $category_image = null;
    var $category_parent_id = null;
    var $category_publish = null;
    var $category_ordertype = null;
    var $category_template = null;
    var $category_ordering = null;
    var $products_sorting = null;
    var $products_sorting2 = null;
    var $category_add_date = null;
    var $products_page = null;
    var $products_row = null;
    function unocartCategory(&$database)
    {
        $this->mosDBTable('#__unocart_categories', 'category_id', $database);
    }

    function getName()
    {
        global $unocartConfig;
        $query = "SELECT IFNULL(cur_lang.category_name, def_lang.category_name) AS category_name
				  FROM `#__unocart_categories` AS cat
				  LEFT JOIN `#__unocart_categories_description` AS cur_lang ON cat.category_id = cur_lang.category_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				  LEFT JOIN `#__unocart_categories_description` AS def_lang ON cat.category_id = def_lang.category_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				  WHERE cat.category_id = '" . $this->category_id . "'";
        $this->_db->setQuery($query);
        return $this->category_name = $this->_db->loadResult();
    }

    function getCountProducts()
    {
        $query = "SELECT pr_cat.product_id
				  FROM `#__unocart_products_to_categories` AS pr_cat
				  INNER JOIN `#__unocart_products` AS prod ON pr_cat.product_id = prod.product_id 
				  WHERE pr_cat.category_id = '" . $this->category_id .
            "' AND prod.product_publish = '1'";
        $this->_db->setQuery($query);
        $this->_db->query();
        return $this->_db->getNumRows();
    }


    function deleteCategory()
    {
        $query = "DELETE FROM `#__unocart_categories`
				   WHERE `category_id` = '" . $this->category_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();

        $query = "DELETE FROM `#__unocart_categories_description`
				   WHERE `category_id` = '" . $this->category_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();

    }

    function getTreeChild()
    {
        $category_parent_id = $this->category_parent_id;
        $i = 0;
        $list_category[$i]->category_id = $this->category_id;
        $list_category[$i++]->category_name = $this->category_name;
        while ($category_parent_id) {
            $category = new unocartCategoryExtend($this->_db);
            $category->load($category_parent_id);
            $list_category[$i]->category_id = $category->category_id;
            $list_category[$i++]->category_name = $category->getName();
            $category_parent_id = $category->category_parent_id;
        }
        $list_category = array_reverse($list_category);
        return $list_category;
    }

    // Static method
    function getAllCategories()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT cat.category_id, cat.category_parent_id
				  FROM `#__unocart_categories` AS cat
				  WHERE cat.category_publish = '1' 
				  ORDER BY cat.category_parent_id";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function getAllCategoriesDescription($parentId, $order = 'id', $ordering = 'asc',
        $publish = 0)
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $add_where = ($publish) ? (" AND cat.category_publish = '1' ") : ("");
        $query = "SELECT IFNULL(cur_lang.category_name, def_lang.category_name) AS category_name, IFNULL(cur_lang.category_description, def_lang.category_description) AS category_description, cat.category_id,cat.category_publish,cat.category_ordering, cat.category_image
				   FROM `#__unocart_categories` AS cat
				   LEFT JOIN `#__unocart_categories_description` AS cur_lang ON cat.category_id = cur_lang.category_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				   LEFT JOIN `#__unocart_categories_description` AS def_lang ON cat.category_id = def_lang.category_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				   WHERE cat.category_parent_id = '" . $parentId . "'" . $add_where . "
				   ORDER BY cat.category_ordering";
        $database->setQuery($query);
        return $categories = $database->loadObjectList();
    }

    function getChildCategories($order, $ordering = 'asc', $publish = 1)
    {
        $cats = unocartCategory::getAllCategoriesDescription($this->category_id, $order,
            $ordering, $publish);
        return $cats;
    }

    function getSisterCategories($order, $ordering = 'asc', $publish = 1)
    {
        $cats = unocartCategory::getAllCategoriesDescription($this->category_parent_id,
            $order, $ordering, $publish);
        return $cats;
    }

    function getTreeParentCategories()
    {
        $category_parent = $this->category_id;
        while ($category_parent) {
            $cats_tree[] = $category_parent;
            $query = "SELECT categ.category_parent_id
					  FROM `#__unocart_categories` AS categ
					  WHERE categ.category_id = '" . $category_parent .
                "' AND categ.category_publish = '1'";
            $this->_db->setQuery($query);
            $rows = $this->_db->loadObjectList();
            $category_parent = $rows[0]->category_parent_id;
        }
        return array_reverse($cats_tree);
    }

    function getProducts($adv = 0, $order1 = null, $orderby1 = null, $order2 = null,
        $orderby2 = null, $limitstart = null, $limit = null)
    {
        global $unocartConfig;
        switch ($adv) {
            case '1':
                $adv_query = " ORDER BY " . $order1 . " " . $orderby1 . ", " . $order2 . " " . $orderby2 .
                    " LIMIT " . $limitstart . ", " . $limit;
                break;
            case '2':
                $adv_query = " ORDER BY " . $order1 . " " . $orderby1 . ", " . $order2 . " " . $orderby2;
                break;
            default:
                $adv_query = "";
        }
        $query = "SELECT prod.product_is_add_price, prod.*, (cur.currency_value*prod.product_price) AS product_price, (prod.product_price*cur.currency_value)/(1+tax.tax_value/100) AS price_netto, IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, IFNULL(cur_lang.product_short_description, def_lang.product_short_description) AS product_short_description 
				  FROM `#__unocart_currencies` AS cur, `#__unocart_products` AS prod
				  LEFT JOIN `#__unocart_products_to_categories` AS categ USING (product_id)
				  LEFT JOIN `#__unocart_products_description` AS cur_lang ON cur_lang.product_id = prod.product_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				  LEFT JOIN `#__unocart_products_description` AS def_lang ON def_lang.product_id = prod.product_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				  INNER JOIN `#__unocart_taxes` AS tax ON tax.tax_id = prod.product_tax_id
				  WHERE categ.category_id = '" . $this->category_id .
            "' AND prod.product_publish = '1' AND cur.currency_id = '" . $unocartConfig->
            cur_currency . "' " . $adv_query;
        $this->_db->setQuery($query);
        $products = $this->_db->loadObjectList();
        foreach ($products as $key => $value) {
            $products[$key]->product_price = unocartProductPrice::correctPrice($products[$key]->
                product_price);
            $products[$key]->product_add_prices = unocartProductPrice::getAddPrices($value->
                product_is_add_price, $value->product_id);
        }
        return $products;
    }

    function check()
    {
        if ($this->category_publish == '')
            $this->category_publish = 0;
    }

    function addLinkToProduct($category_id)
    {
        $this->product_link = SEFLink('index.php?option=com_unocart&task=product&product_id=' .
            $this->product_id . '&category_id=' . $category_id);
    }
}

class unocartCategoryExtend extends unocartCategory
{
    var $category_description = null;
    var $category_name = null;
    var $category_meta_title = null;
    var $category_meta_keyword = null;
    var $category_meta_description = null;

    function getExtendsData()
    {
        global $unocartConfig;
        $query = "SELECT IFNULL(cur_descr.category_name, def_descr.category_name) AS category_name, IFNULL(cur_descr.category_description, def_descr.category_description) AS category_description, IFNULL(cur_descr.category_meta_title, def_descr.category_meta_title) AS category_meta_title, IFNULL(cur_descr.category_meta_description, def_descr.category_meta_description) AS category_meta_description, IFNULL(cur_descr.category_meta_keyword, def_descr.category_meta_keyword) AS category_meta_keyword
				  FROM `#__unocart_categories` AS categ
				  LEFT JOIN `#__unocart_categories_description` AS cur_descr ON cur_descr.category_id = categ.category_id AND cur_descr.language = '" .
            $unocartConfig->cur_lang . "'
				  LEFT JOIN `#__unocart_categories_description` AS def_descr ON def_descr.category_id = categ.category_id AND def_descr.language = '" .
            $unocartConfig->defaultLanguage . "'
				  WHERE categ.category_id = '" . $this->category_id . "'";
        $this->_db->setQuery($query);
        $this->_db->loadObject($row);
        $this->category_description = $row->category_description;
        $this->category_name = $row->category_name;
        $this->category_meta_title = $row->category_meta_title;
        $this->category_meta_keyword = $row->category_meta_keyword;
        $this->category_meta_description = $row->category_meta_description;
    }
}

class unocartCurrency extends mosDBTable
{
    var $currency_id = null;
    var $currency_name = null;
    var $currency_code = null;
    var $currency_ordering = null;
    var $currency_value = null;
    var $currency_publish = null;
    function unocartCurrency(&$database)
    {
        $this->mosDBTable('#__unocart_currencies', 'currency_id', $database);
    }

    // Static method
    function getAllCurrencies($publish = 1)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("WHERE currencies.currency_publish = '1'") : ("");
        $query = "SELECT currencies.*
				  FROM `#__unocart_currencies` AS currencies
				  $query_where
				  ORDER BY currencies.currency_ordering";
        $database->setQuery($query);
        return $database->loadObjectList();
    }
}

class unocartCountry extends mosDBTable
{
    var $country_id = null;
    var $country_publish = null;
    var $country_ordering = null;
    var $country_name = null;
    var $country_code = null;

    function unocartCountry(&$database)
    {
        $this->mosDBTable('#__unocart_countries', 'country_id', $database);
    }
    // Static method
    function getAllCountries($publish = 1, $limitstart = -1, $limit = -1)
    {
        $database = &unocartFactory::getDBO();
        $where = ($publish) ? (" WHERE countries.country_publish = '1' ") : (" ");
        $limit = ($limitstart >= 0 && $limit > 0) ? (" LIMIT " . $limitstart . ", " . $limit) : ("");
        $query = "SELECT countries.*
				  FROM `#__unocart_countries` AS countries" . $where . "
				  ORDER BY countries.country_ordering" . $limit;
        $database->setQuery($query);
        return $rows = $database->loadObjectList();
    }

    // Static method
    function getCountAllCountries()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT COUNT(countries.country_id)
				  FROM `#__unocart_countries` AS countries";
        $database->setQuery($query);
        return $database->loadResult();
    }
}
/*
class unocartLanguage extends mosDBTable{
var $language_id		= null;
var $language_name 		= null;
var $language_code		= null;
var $language_ordering	= null;
var $language_publish	= null;
function unocartLanguage(&$database){
$this->mosDBTable('#__unocart_languages', 'language_id', $database);
}
}
*/
class unocartTax extends mosDBTable
{
    var $tax_id = null;
    var $tax_name = null;
    var $tax_value = null;
    function unocartTax(&$database)
    {
        $this->mosDBTable('#__unocart_taxes', 'tax_id', $database);
    }

    // Static method
    function getAllTaxes()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT tax.*
				  FROM `#__unocart_taxes` AS tax";
        $database->setQuery($query);
        return $database->loadObjectList();
    }
}

class unocartProduct extends mosDBTable
{
    var $product_id = null;
    var $product_ean = null;
    var $product_quantity = null;
    var $product_availability = null;
    var $product_date_added = null;
    var $product_publish = null;
    var $product_tax_id = null;
    var $product_template = null;
    var $product_url = null;
    var $product_price = null;
    var $product_old_price = null;
    var $product_buy_price = null;
    var $product_weight = null;
    var $product_thumb_image = null;
    var $product_full_image = null;
    var $product_manufacturer_id = null;
    var $product_count_related = null;
    var $product_special_type = null;
    var $product_download_file = null;
    var $product_download_description = null;
    var $product_is_add_price = null;
    var $product_show_price = 0;

    function unocartProduct(&$database)
    {
        $this->mosDBTable('#__unocart_products', 'product_id', $database);
    }

    function getAllProducts($category_id, $product_id = null, $limitstart = null, $limit = null,
        $text_search = null)
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $where = ($product_id) ? ("AND pr.product_id <> '" . $product_id . "' ") : ('');
        if ($limit > 0) {
            $limit = " LIMIT " . $limitstart . " , " . $limit;
        }
        $where .= ($text_search) ? (" AND CONCAT_WS('|',cur_lang.product_name,cur_lang.product_short_description, cur_lang.product_description ) LIKE '%" .
            $text_search . "%' ") : ('');

        if ($category_id) {
            $query = "SELECT pr.product_id, pr.product_publish, pr_cat.product_ordering, IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, IFNULL(cur_lang.product_short_description, def_lang.product_short_description) AS product_short_description
					  FROM `#__unocart_products` AS pr
					  LEFT JOIN `#__unocart_products_to_categories` AS pr_cat USING (product_id)
					  LEFT JOIN `#__unocart_products_description` AS cur_lang ON cur_lang.product_id = pr.product_id AND cur_lang.language = '" .
                $unocartConfig->cur_lang . "'
					  LEFT JOIN `#__unocart_products_description` AS def_lang ON def_lang.product_id = pr.product_id AND def_lang.language = '" .
                $unocartConfig->defaultLanguage . "'
					  WHERE pr_cat.category_id = '" . $category_id . "'" . $where . "
					  GROUP BY pr.product_id
					  ORDER BY pr_cat.product_ordering ASC" . $limit;
        } else {
            $query = "SELECT pr.product_id, pr.product_publish, IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, IFNULL(cur_lang.product_short_description, def_lang.product_short_description) AS product_short_description 
					  FROM `#__unocart_products` AS pr
					  LEFT JOIN `#__unocart_products_description` AS cur_lang ON cur_lang.product_id = pr.product_id AND cur_lang.language = '" .
                $unocartConfig->cur_lang . "'
					  LEFT JOIN `#__unocart_products_description` AS def_lang ON def_lang.product_id = pr.product_id AND def_lang.language = '" .
                $unocartConfig->defaultLanguage . "'
					  WHERE 1 " . $where . "
					  ORDER BY pr.product_id" . $limit;
        }
        $database->setQuery($query);
        return $all_products = $database->loadObjectList();
    }

    function getCountAllProducts($category_id, $text_search = null)
    {
        $database = &unocartFactory::getDBO();
        if ($text_search) {
            $join = " LEFT JOIN `#__unocart_products_description` AS prod_descr ON prod_descr.product_id = prod.product_id ";
            $where = "AND CONCAT_WS('|', prod_descr.product_name, prod_descr.product_short_description, prod_descr.product_description) LIKE '%" .
                $text_search . "%'";
        } else {
            $join = '';
            $where = '';
        }
        if ($category_id) {
            $query = "SELECT DISTINCT prod.product_id
					 FROM `#__unocart_products` AS prod INNER JOIN `#__unocart_products_to_categories` AS prod_cat USING (product_id)" .
                $join . "
					 WHERE prod_cat.category_id = '" . $category_id . "'" . $where;
        } else {
            $query = "SELECT DISTINCT prod.product_id
					 FROM `#__unocart_products` AS prod" . $join . "
					 WHERE 1 " . $where;
        }
        $database->setQuery($query);
        $database->query();
        return $database->getAffectedRows();
    }

    // Static method
    // Get last or random products
    function getLastProducts($count, $array_categories = null, $rand = 0)
    {
        global $unocartConfig, $my;
        $discount_percent = unocartUser::getDiscount($my->id);
        $where_add = '';
        if (count($array_categories)) {
            $where_add = " AND (";
            foreach ($array_categories as $key => $value) {
                $where_add .= " pr_cat.category_id = '" . $value . "' OR ";
            }
            $where_add = Jstring::substr($where_add, 0, Jstring::strlen($where_add) - 4);
            $where_add .= ")";
        }
        $database = &unocartFactory::getDBO();
        $order_add = ($rand) ? ("RAND()") : ("prod.product_date_added DESC");
        $query = "SELECT IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, prod.product_id, prod.product_ean, prod.product_url, prod.product_thumb_image, prod.product_full_image, pr_cat.category_id, (prod.product_price*" .
            $unocartConfig->currency_value . ") AS product_price, product_is_add_price
				  FROM `#__unocart_products` AS prod
				  INNER JOIN `#__unocart_products_to_categories` AS pr_cat ON pr_cat.product_id = prod.product_id
				  LEFT JOIN `#__unocart_products_description` AS cur_lang ON prod.product_id = cur_lang.product_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				  LEFT JOIN `#__unocart_products_description` AS def_lang ON prod.product_id = def_lang.product_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				  WHERE prod.product_publish = '1'" . $where_add . "
				  GROUP BY prod.product_id
				  ORDER BY " . $order_add . "
				  LIMIT " . $count;
        $database->setQuery($query);
        $products = $database->loadObjectList();
        foreach ($products as $key => $value) {
            $products[$key]->product_price = unocartProductPrice::correctPrice($products[$key]->
                product_price);
            $products[$key]->product_add_prices = unocartProductPrice::getAddPrices($value->
                product_is_add_price, $value->product_id, $discount_percent);
        }
        return $products;
    }

    // Static method
    function getRandomProducts($count, $array_categories)
    {
        return unocartProduct::getLastProducts($count, $array_categories, 1);
    }

    function getAttributes()
    {
        global $unocartConfig;
        $query = "SELECT pr_attr.value_price, attr.attr_name, attr.attr_id, valu.value_id, valu.value_name, attr_to_val.value_id_to_attr_id, pr_attr.price_prefix, attr.attr_type, valu.image, attr.language AS language_attr, valu.language AS language_valu
				  FROM `#__unocart_products_attr` AS pr_attr
				  INNER JOIN `#__unocart_attr_to_values` AS attr_to_val ON pr_attr.attr_value_id = attr_to_val.value_id_to_attr_id
				  INNER JOIN `#__unocart_attr` AS attr ON attr.attr_id = attr_to_val.attr_id
				  INNER JOIN `#__unocart_attr_values` AS valu ON attr_to_val.value_id = valu.value_id
				  WHERE pr_attr.product_id = '" . $this->product_id . "'
				  ORDER BY attr.attr_ordering, valu.value_ordering, language_attr, language_valu";
        $this->_db->setQuery($query);
        $all_values = $this->_db->loadObjectList();
        $values = array();
        foreach ($all_values as $value) {
            $values[$value->value_id][$value->language_attr . $value->language_valu] = $value;
        }

        $rows = array();
        foreach ($values as $value) {
            if (isset($value[$unocartConfig->cur_lang . $unocartConfig->cur_lang])) {
                $rows[] = $value[$unocartConfig->cur_lang . $unocartConfig->cur_lang];
            } else
                if (isset($value[$unocartConfig->defaultLanguage . $unocartConfig->
                    defaultLanguage])) {
                    $rows[] = $value[$unocartConfig->defaultLanguage . $unocartConfig->
                        defaultLanguage];
                } else {
                    $obj = array_shift($value);
                    $rows[] = $obj;
                }
        }
        return $rows;
    }

    function getCategories()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT *
				   FROM `#__unocart_products_to_categories` AS pr_cat
				   WHERE pr_cat.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function getMaxOrdering($category_id)
    {
        $query = "SELECT MAX(prod_cat.product_ordering)
				 FROM `#__unocart_products_to_categories` AS prod_cat
				 WHERE prod_cat.category_id = '" . $category_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }

    function existRelation($category_id)
    {
        $query = "SELECT prod_cat.category_id
				   FROM `#__unocart_products_to_categories` AS prod_cat
				   WHERE prod_cat.product_id = '" . $this->product_id .
            "' AND prod_cat.category_id = '" . $category_id . "'";
        $this->_db->setQuery($query);
        $res = $this->_db->query();
        return $this->_db->getNumRows($res);
    }

    function addRelationCategories($array_category_id)
    {
        foreach ($array_category_id as $key => $value) {
            if (!$this->existRelation($value)) {
                $query = "INSERT INTO `#__unocart_products_to_categories`
					  SET `product_id` = '" . $this->product_id . "', `category_id` = '" . $value .
                    "', `product_ordering` = '" . intval($this->getMaxOrdering($value) + 1) . "'";
                $this->_db->setQuery($query);
                $this->_db->query();
            }
        }

        $all_relations = $this->getAllRelations();
        if (count($all_relations)) {
            foreach ($all_relations as $relat) {
                $arr[] = $relat->category_id;
            }
        }
        $this->deleteRelations(array_diff($arr, $array_category_id));
    }

    // funkcija, yaka vyluchae lyshni relations
    function deleteRelations($array_id)
    {
        if (count($array_id)) {
            foreach ($array_id as $key => $value) {
                $query = "DELETE FROM `#__unocart_products_to_categories`
					  WHERE `product_id` = '" . $this->product_id . "' AND `category_id` = '" .
                    $value . "'";
                $this->_db->setQuery($query);
                $this->_db->query();
            }
        }
    }

    function getAllRelations()
    {
        $query = "SELECT categ.category_id
				FROM `#__unocart_products_to_categories` AS categ
				WHERE categ.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();

    }

    function addLinkToRelatedProducts()
    {
        if (count($this->product_related))
            foreach ($this->product_related as $key => $value) {
                $this->product_related[$key]->product_link = SEFLink('index.php?option=com_unocart&task=product&product_id=' .
                    $value->product_id . '&category_id=' . $value->category_id);
            }
    }


    function getName()
    {
        global $unocartConfig;
        $query = "SELECT IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name
				FROM `#__unocart_products` AS prod
				LEFT JOIN `#__unocart_products_description` AS cur_lang ON prod.product_id = cur_lang.product_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				LEFT JOIN `#__unocart_products_description` AS def_lang ON prod.product_id = def_lang.product_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				WHERE prod.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }

    // Static method
    function updateProductInStock($arrProd)
    {
        $database = &unocartFactory::getDBO();
        foreach ($arrProd as $prod) {
            $query = "UPDATE `#__unocart_products` AS prod
					  SET prod.product_quantity = product_quantity - " . $prod['quantity'] . "
					  WHERE prod.product_id = '" . $prod['product_id'] . "'";
            $database->setQuery($query);
            if (!$database->query()) {
                //echo $database->_errorMsg;
                exit();
            }
        }
    }

    function getReviews()
    {
        $query = "SELECT *
				  FROM `#__unocart_products_reviews` AS rev
				  WHERE rev.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function getAverageRating()
    {
        $query = "SELECT ROUND(AVG(review.mark),2)
				  FROM `#__unocart_products_reviews` AS review
				  WHERE review.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }

    function getPriceWithAttributes($price, $attr_id, $value_id)
    {
        global $unocartConfig;
        $query = "SELECT (product_attr.value_price * " . $unocartConfig->currency_value .
            ") AS value_price , product_attr.price_prefix
				  FROM `#__unocart_attr_to_values` AS attr_to_values
				  INNER JOIN `#__unocart_products_attr` AS product_attr ON attr_to_values.value_id_to_attr_id = product_attr.attr_value_id
				  WHERE attr_to_values.attr_id = '" . $attr_id .
            "' AND attr_to_values.value_id = '" . $value_id .
            "' AND product_attr.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        $this->_db->loadObject($row);
        switch ($row->price_prefix) {
            case '+':
                $price += $row->value_price;
                break;
            case '=':
                $price = $row->value_price;
                break;
            case '-':
                $price -= $row->value_price;
                break;
        }
        return $price;
    }

    function getImages()
    {
        global $unocartConfig;
        $query = "SELECT images.image_thumb, images.image_name, images.image_id
				FROM `#__unocart_products_images` AS images
				WHERE images.product_id = '" . $this->product_id . "'
				ORDER BY images.product_id";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function getVideos()
    {
        global $unocartConfig;
        $query = "SELECT  videos.video_name, videos.video_id, videos.video_preview
				FROM `#__unocart_products_videos` AS videos
				WHERE videos.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function setMainImage($array_images)
    {
        if (count($array_images)) {
            $this->product_thumb_image = $array_images[0]->image_thumb;
            $this->product_full_image = $array_images[0]->image_name;
        } else {
            $this->product_thumb_image = 'no_image.gif';
            $this->product_full_image = 'no_image.gif';
        }
    }

    function getRelatedProducts($is_front)
    {
        // if $is_front == 1 - for frontend (with price and name)
        // if $is_front == 0 - for admin  (ohne price)
        global $unocartConfig;
        if ($is_front) {
            $query = "SELECT relation.product_related_id AS product_id, (prod.product_price*" .
                $unocartConfig->currency_value .
                ") AS product_price, pr_cat.category_id, prod.product_thumb_image, IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, prod.product_is_add_price
					FROM `#__unocart_products_relations` AS relation
					INNER JOIN `#__unocart_products` AS prod ON relation.product_related_id = prod.product_id
					LEFT JOIN `#__unocart_products_to_categories` AS pr_cat ON pr_cat.product_id = relation.product_related_id
					LEFT JOIN `#__unocart_products_description` AS cur_lang ON cur_lang.product_id = prod.product_id AND cur_lang.language = '" .
                $unocartConfig->cur_lang . "' 
					LEFT JOIN `#__unocart_products_description` AS def_lang ON def_lang.product_id = prod.product_id AND def_lang.language = '" .
                $unocartConfig->defaultLanguage . "'
					WHERE relation.product_id = '" . $this->product_id .
                "' AND prod.product_publish = '1'
					GROUP BY product_id";
        } else {
            $query = "SELECT relation.product_related_id AS product_id, prod.product_is_add_price
					FROM `#__unocart_products_relations` AS relation
					LEFT JOIN `#__unocart_products` AS prod USING (product_id)
					WHERE prod.product_id = '" . $this->product_id .
                "' AND prod.product_publish = '1' AND relation.product_id = prod.product_id";
        }
        $this->_db->setQuery($query);

        $products = $this->_db->loadObjectList();
        foreach ($products as $key => $value) {
            $products[$key]->product_add_prices = unocartProductPrice::getAddPrices($value->
                product_is_add_price, $value->product_id);
        }
        return $this->product_related = $products;
    }

    function getDownloadFile()
    {
        $query = "SELECT prod.product_download_file AS file
				  FROM `#__unocart_products` AS prod
				  WHERE prod.product_id = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }

    function getSpecialType()
    {
        if ($this->product_special_type) {
            $query = "SELECT *
					  FROM `#__unocart_products_sp_type_info` AS sp_type_info
					  WHERE sp_type_info.product_id = '" . $this->product_id . "'
					  ORDER BY sp_type_info.field_1";
            $this->_db->setQuery($query);
            return $this->_db->loadObjectList();
        } else {
            return null;
        }
    }

    function processSpecialType()
    {
        if ($this->product_special_type) {
            $delete = mosGetParam($_POST, 'delete');
            if (count($delete)) {
                $this->deleteSpecialField($delete);
            }
            $this->saveSpecialField();
        }
    }

    function deleteSpecialField($array_delete)
    {
        call_user_func(array('JSpecial_' . $this->product_special_type, 'delete'), $array_delete);
    }

    function saveSpecialField()
    {
        call_user_func(array('JSpecial_' . $this->product_special_type, 'save'), $this->
            product_id);
    }

    function getAddPrices()
    {
        $query = "SELECT *
				  FROM `#__unocart_products_prices` AS add_prices
				  WHERE add_prices.product_id = '" . $this->product_id . "'
				  ORDER BY add_prices.product_quantity_start DESC";
        $this->_db->setQuery($query);
        $this->product_add_prices = $this->_db->loadObjectList();
        foreach ($this->product_add_prices as $key => $value) {
            $this->product_add_prices[$key]->product_price = unocartProductPrice::
                correctPrice($value->product_price);
        }
    }

    function updateAddPrice($product_add_price, $quantity_start, $quantity_finish, $product_add_price_delete,
        $product_is_add_price)
    {
        $query = "DELETE FROM `#__unocart_products_prices`
				  WHERE `product_id` = '" . $this->product_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
        $counter = 0;
        if (count($product_add_price) && $product_is_add_price) {
            foreach ($product_add_price as $key => $value) {
                if (isset($product_add_price_delete[$key]) || ((!$quantity_start[$key] && !$quantity_finish[$key])))
                    continue;
                $query = "INSERT INTO `#__unocart_products_prices`
						  SET `product_id` = '" . $this->product_id . "',
							  `product_price` = '" . $product_add_price[$key] . "',
							  `product_quantity_start` = '" . $quantity_start[$key] . "',
							  `product_quantity_finish` = '" . $quantity_finish[$key] . "'";
                $this->_db->setQuery($query);
                if ($this->_db->query())
                    $counter++;
            }
        }
        $this->product_is_add_price = ($counter) ? (1) : (0);
    }

    function getBestProducts($product_ids)
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        if (Jstring::strlen($product_ids)) {
            $where_add = " AND prod.product_id IN (" . $product_ids . ")";
            $query = "SELECT IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, prod.product_id, prod.product_ean, prod.product_url, prod.product_thumb_image, pr_cat.category_id, (prod.product_price*" .
                $unocartConfig->currency_value . ") AS product_price
					  FROM `#__unocart_products` AS prod
					  INNER JOIN `#__unocart_products_to_categories` AS pr_cat ON pr_cat.product_id = prod.product_id
					  LEFT JOIN `#__unocart_products_description` AS cur_lang ON prod.product_id = cur_lang.product_id AND cur_lang.language = '" .
                $unocartConfig->cur_lang . "'
					  LEFT JOIN `#__unocart_products_description` AS def_lang ON prod.product_id = def_lang.product_id AND def_lang.language = '" .
                $unocartConfig->defaultLanguage . "'
					  WHERE prod.product_publish = '1'" . $where_add . "
					  GROUP BY prod.product_id
					  ORDER BY prod.product_id";
            $database->setQuery($query);
            return $database->loadObjectList();
        }
    }

}

class unocartProductExtend extends unocartProduct
{
    var $product_description = null;
    var $product_short_description = null;
    var $product_name = null;
    var $product_meta_title = null;
    var $product_meta_keyword = null;
    var $product_meta_description = null;
    var $product_related = null;
    var $product_images = null;
    var $product_videos = null;
    var $product_tax = null;
    var $category_id = null;
    var $product_attributes = null;

    function getTax()
    {
        global $unocartConfig;
        $query = "SELECT tax.tax_value
				  FROM `#__unocart_products` AS prod
				  LEFT JOIN `#__unocart_taxes` AS tax ON prod.product_tax_id = tax.tax_id
				  WHERE prod.product_id = '" . $this->product_id . "'
				  LIMIT 0,1";
        $this->_db->setQuery($query);
        $this->_db->loadObject($row);
        $this->product_tax = $row->tax_value;
    }

    function getCategory()
    {
        $query = "SELECT cat.category_id
				FROM `#__unocart_products_to_categories` AS cat
				WHERE cat.product_id = '" . $this->product_id . "'
				LIMIT 0,1";
        $this->_db->setQuery($query);
        $this->category_id = $this->_db->loadResult();
    }
    function getExtendsData()
    {
        $this->getRelatedProducts(1);
        $this->getDescriptionPrice();
    }

    function getDescriptionPrice($quantity = 0)
    {
        global $unocartConfig;
        $query = "SELECT (prod.product_price*" . $unocartConfig->currency_value .
            ") AS product_price, tax.tax_value, 
				IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, IFNULL(cur_lang.product_short_description, def_lang.product_short_description) AS product_short_description, IFNULL(cur_lang.product_description, def_lang.product_description) AS product_description,
				IFNULL(cur_lang.product_meta_title, def_lang.product_meta_title) AS product_meta_title, IFNULL(cur_lang.product_meta_keyword, def_lang.product_meta_keyword) AS product_meta_keyword, IFNULL(cur_lang.product_meta_description, def_lang.product_meta_description) AS product_meta_description      
				FROM `#__unocart_products` AS prod
				LEFT JOIN `#__unocart_taxes` AS tax ON prod.product_tax_id = tax.tax_id
				LEFT JOIN `#__unocart_products_description` AS cur_lang ON prod.product_id = cur_lang.product_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				LEFT JOIN `#__unocart_products_description` AS def_lang ON prod.product_id = def_lang.product_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				WHERE prod.product_id = '" . $this->product_id .
            "' AND prod.product_publish = '1'
				LIMIT 0,1";
        $this->_db->setQuery($query);
        $this->_db->loadObject($product);
        $this->getAddPrices();
        if ($quantity && $this->product_is_add_price) {
            foreach ($this->product_add_prices as $key => $value) {
                if ($quantity >= $value->product_quantity_start) {
                    $this->product_price = $value->product_price;
                    break;
                }
            }
        } else {
            $this->product_price = unocartProductPrice::correctPrice($product->
                product_price);
        }
        $this->product_tax = $product->tax_value;
        $this->product_short_description = $product->product_short_description;
        $this->product_description = $product->product_description;
        $this->product_name = $product->product_name;
        $this->product_meta_title = $product->product_meta_title;
        $this->product_meta_keyword = $product->product_meta_keyword;
        $this->product_meta_description = $product->product_meta_description;
    }

    function getPrice($quantity)
    {
        global $unocartConfig;
        $query = "SELECT (prod.product_price*" . $unocartConfig->currency_value .
            ") AS product_price
				FROM `#__unocart_products` AS prod
				LEFT JOIN `#__unocart_taxes` AS tax ON prod.product_tax_id = tax.tax_id
				WHERE prod.product_id = '" . $this->product_id .
            "' AND prod.product_publish = '1'
				LIMIT 0,1";
        $this->_db->setQuery($query);
        $product_price = $this->_db->loadResult();
        $this->getAddPrices();
        if ($quantity && $this->product_is_add_price) {
            foreach ($this->product_add_prices as $key => $value) {
                if ($quantity >= $value->product_quantity_start) {
                    $this->product_price = $value->product_price;
                    break;
                }
            }
        } else {
            $this->product_price = unocartProductPrice::correctPrice($product_price);
        }

        return $this->product_price;
    }
}


class unocartProductPrice extends mosDBTable
{
    var $price_id = null;
    var $product_id = null;
    var $product_price = null;
    var $product_quantity_start = null;
    var $product_quantity_finish = null;

    function unocartProductPrice(&$database)
    {
        $this->mosDBTable('#__unocart_products_price', 'price_id', $database);
    }

    // Static method
    function getAddPrices($product_is_add_price, $product_id, $discount_percent = 1)
    {
        if (!$product_is_add_price)
            return;
        $database = &unocartFactory::getDBO();
        $query = "SELECT product.*
				  FROM `#__unocart_products_prices` AS product
				  WHERE product.product_id = '" . $product_id . "'
				  ORDER BY product.product_quantity_start DESC";
        $database->setQuery($query);
        $add_prices = $database->loadObjectList();
        foreach ($add_prices as $key => $value) {
            $add_prices[$key]->product_price *= (1 - $discount_percent);
        }
        return $add_prices;
    }

    // Static method
    // Method koregue price, zalezhno vid discounta, ne znav v jakyj klas krache pidhodyt cej metod, to zasunuv syudy
    function correctPrice($product_price)
    {
        global $my;
        $discount_percent = unocartUser::getDiscount($my->id);
        return (1 - $discount_percent) * $product_price;
    }
}

class unocartConfig extends mosDBTable
{
    var $id = null;
    var $count_products_to_page = null;
    var $count_products_to_row = null;
    var $count_category_to_row = null;
    var $image_category_width = null;
    var $image_category_height = null;
    var $image_product_width = null;
    var $image_product_height = null;
    var $image_product_full_width = null;
    var $image_product_full_height = null;
    var $image_category_path = null;
    var $image_product_path = null;
    var $video_product_path = null;
    var $image_product_live_path = null;
    var $image_manufs_path = null;
    var $image_manufs_live_path = null;
    var $video_product_live_path = null;
    var $default_status_order = null;
    var $mainLanguage = null;
    var $defaultLanguage = null;
    var $mainCurrency = null;
    var $admin_path = null;
    var $decimal_count = null;
    var $decimal_symbol = null;
    var $thousand_separator = null;
    var $currency_format = null;
    var $use_rabatt_code = null;
    var $enable_wishlist = null;
    var $remove_prod_f_wishlist = null;
    var $order_number_type = null;

    var $store_name = null;
    var $store_company_name = null;
    var $store_url = null;
    var $store_address = null;
    var $store_city = null;
    var $store_zip = null;
    var $store_country = null;
    var $store_state = null;
    var $store_address_format = null;
    var $store_date_format = null;

    var $contact_firstname = null;
    var $contact_lastname = null;
    var $contact_middlename = null;
    var $contact_phone = null;
    var $contact_fax = null;
    var $contact_email = null;

    var $benef_bank_info = null;
    var $benef_bic = null;
    var $benef_conto = null;
    var $benef_iban = null;
    var $benef_swift = null;
    var $interm_name = null;
    var $interm_swift = null;
    var $shop_special_type = null;
    var $allow_reviews_prod = null;
    var $allow_reviews_manuf = null;
    var $allow_reviews_only_registered = null;
    var $max_mark = null;
    var $summ_null_shipping = null;
    var $without_shipping = 0;
    var $pdf_parameters;


    function unocartConfig(&$database)
    {
        $this->mosDBTable('#__unocart_config', 'id', $database);
    }

    function transformPdfParameters()
    {
        $this->pdf_parameters = implode(":", $this->pdf_parameters);
    }
}
class unocartImage extends mosDBTable
{
    var $image_id = null;
    var $product_id = null;
    var $image_thumb = null;
    var $image_name = null;
    function unocartImage(&$database)
    {
        $this->mosDBTable('#__unocart_products_images', 'image_id', $database);
    }
}

class Cart
{
    var $db;
    var $products = array();
    var $id = null;
    var $rabatt_value = null;
    var $rabatt_type = null;
    var $rabatt_summ = null;
    var $summ = 0;
    var $count_product = 0;
    function Cart()
    {
        global $my, $database, $unocartConfig;
        $this->_db = $database;
        if (isset($_COOKIE['unocart_temp_cart'])) {
            $products = unocartTempCart::getTempCart($_COOKIE['unocart_temp_cart']);
            if (count($products)) {
                $this->products = $products;
                $this->saveToSession();
                return;
            }
        }
        if (isset($_SESSION['cart'])) {
            $temp_cart = $_SESSION['cart'];
            $this->products = $temp_cart->products;
            $this->id = $temp_cart->id;
            $this->rabatt_value = $temp_cart->rabatt_value;
            $this->rabatt_type = $temp_cart->rabatt_type;
            $this->rabatt_summ = $temp_cart->rabatt_summ;
        } else {
            $this->products = array();
            $this->id = 0;
            $this->rabatt_value = 0;
            $this->rabatt_type = 0;
            $this->rabatt_summ = 0;
        }
    }

    function getSum()
    {
        $this->summ = $this->count_product = 0;
        if (count($this->products)) {
            foreach ($this->products as $prod) {
                $this->summ += $prod['price'] * $prod['quantity'];
                $this->count_product += $prod['quantity'];
            }
        }
        return $this->summ + $price_shipping = (isset($_SESSION['unocart_price_shipping'])) ? ($_SESSION['unocart_price_shipping']) : (0);
    }

    function getSumNetto()
    {
        $summ = 0;
        foreach ($this->products as $prod) {
            $summ += $prod['price_netto'] * $prod['quantity'];
        }
        return round($summ, 2);
    }

    function getShippingPrice()
    {
        return $_SESSION['unocart_price_shipping'];
    }

    function getShippingNettoPrice()
    {
        return $_SESSION['unocart_price_shipping'] / (1 + $_SESSION['unocart_price_shipping_tax_percent'] /
            100);
    }


    function getTax()
    {
        global $database;
        $tax_summ = 0;
        foreach ($this->products as $key => $value) {
            $tax_summ += $value['quantity'] * ($value['price'] - $value['price'] / (1 + $value['tax'] /
                100));
        }
        $tax_summ += (isset($_SESSION['unocart_price_shipping_tax'])) ? $_SESSION['unocart_price_shipping_tax'] : (0);
        return $tax_summ;
    }

    function getDifferentTax()
    {
        $arr_taxes = array();
        foreach ($this->products as $key => $value) {
            if (!isset($arr_taxes[$value['tax']])) {
                $arr_taxes[$value['tax']] = $value['quantity'] * ($value['price'] - $value['price'] /
                    (1 + $value['tax'] / 100));
            } else {
                $arr_taxes[$value['tax']] += $value['quantity'] * ($value['price'] - $value['price'] /
                    (1 + $value['tax'] / 100));
            }
        }

        if (isset($_SESSION['unocart_price_shipping_tax_percent'])) {
            if (!$_SESSION['unocart_price_shipping_tax_percent'])
                return $arr_taxes;
            $shipping_tax_value = $_SESSION['unocart_price_shipping_tax_percent'];
            if (isset($arr_taxes[$shipping_tax_value])) {
                $arr_taxes[$shipping_tax_value] += $_SESSION['unocart_price_shipping_tax'];
            } else {
                $arr_taxes[$shipping_tax_value] = $_SESSION['unocart_price_shipping_tax'];
            }
        }
        return $arr_taxes;
    }

    function calcNettoPrice()
    {
        foreach ($this->products as $key => $value) {
            $this->products[$key]['price_netto'] = round($value['price'] / (1 + $value['tax'] /
                100), 2);
        }
    }

    function refreshCartWithNewCurrency($currency_value)
    {
        foreach ($this->products as $key => $value) {
            $product = new unocartProductExtend($this->_db);
            $product->load($this->products[$key]['product_id']);
            $this->products[$key]['price'] = $product->getPrice($this->products[$key]['quantity']);
            if (is_array($attr_id = unserialize($value['attributes']))) {
                foreach ($attr_id as $key2 => $value2) {
                    $this->products[$key]['price'] = $product->getPriceWithAttributes($this->
                        products[$key]['price'], $key2, $value2);
                }
            }
        }
        $this->saveToSession();
    }

    function add($product_id, $quantity, $attr_id)
    {
        global $unocartConfig;
        $attr_serialize = serialize($attr_id);
        if ($quantity <= 0)
            return 0;
        $currency = new unocartCurrency($this->_db);
        $currency->load($unocartConfig->cur_currency);

        $new_product = 1;
        foreach ($this->products as $key => $value) {
            if ($value['product_id'] == $product_id && $value['attributes'] == $attr_serialize) {
                $this->products[$key]['quantity'] += $quantity;
                $new_product = 0;
                break;
            }
        }

        if ($new_product) {
            $product = new unocartProductExtend($this->_db);
            $product->load($product_id);
            if (!$product->product_show_price)
                return;
            $product->getDescriptionPrice($quantity);
            $product->getCategory();
            $temp_product['quantity'] = $quantity;
            $temp_product['product_id'] = $product_id;
            $temp_product['category_id'] = $product->category_id;
            $temp_product['price'] = $product->product_price;
            $temp_product['tax'] = $product->product_tax;
            $temp_product['description'] = $product->product_short_description;
            $temp_product['product_name'] = $product->product_name;
            $temp_product['thumb_image'] = $product->product_thumb_image;
            $temp_product['ean'] = $product->product_ean;
            $temp_product['attributes'] = $attr_serialize;
            $temp_product['weight'] = $product->product_weight;
            $i = 0;
            if (is_array($attr_id)) {
                foreach ($attr_id as $key => $value) {
                    $attr = new unocartAttribut($this->_db);
                    $attr_v = new unocartValue($this->_db);
                    $temp_product['attributes_value'][$i]->attr = $attr->getName($key);
                    $temp_product['attributes_value'][$i++]->value = $attr_v->getName($value);
                    $temp_product['price'] = $product->getPriceWithAttributes($temp_product['price'],
                        $key, $value);
                }
            }
            // ------------------------------------------------------
            $this->products[] = $temp_product;
        }
        $this->setRabatt($this->rabatt_type, $this->rabatt_value);
        return 1;
    }

    function refresh($quantity)
    {
        if (is_array($quantity) && count($quantity)) {
            foreach ($quantity as $key => $value) {
                $product = new unocartProductExtend($this->_db);
                $product->load($this->products[$key]['product_id']);
                $product->getPrice($value);
                if (isset($this->products[$key]['attributes'])) {
                    $attr = unserialize($this->products[$key]['attributes']);
                    if (is_array($attr)) {
                        foreach ($attr as $key2 => $value2) {
                            $product->product_price = $product->getPriceWithAttributes($product->getPrice($value),
                                $key2, $value2);
                        }
                    }
                    $this->products[$key]['price'] = $product->product_price;
                }
                $this->products[$key]['quantity'] = $value;
                if ($this->products[$key]['quantity'] == 0)
                    unset($this->products[$key]);
            }
        }
        $this->setRabatt($this->rabatt_type, $this->rabatt_value);
    }

    function getWeightProducts()
    {
        $weight_sum = 0;
        foreach ($this->products as $prod) {
            $weight_sum += $prod['weight'] * $prod['quantity'];
        }
        return $weight_sum;
    }

    function setRabatt($type, $value)
    {
        global $unocartConfig;
        $this->rabatt_type = $type;
        $this->rabatt_value = $value;
        $this->getSum();
        if ($this->rabatt_type == 1) {
            // When value rabatt
            $this->rabatt_summ = $this->rabatt_value * $unocartConfig->currency_value;
        } else {
            // When percent rabatt
            $this->rabatt_summ = $this->rabatt_value / 100 * $this->summ;
        }
        $this->saveToSession();
    }

    function addLinkToProducts($show_delete = 0)
    {
        foreach ($this->products as $key => $value) {
            $this->products[$key]['href'] = SEFLink('index.php?option=com_unocart&task=product&product_id=' .
                $value['product_id'] . '&category_id=' . $this->products[$key]['category_id']);
            if ($show_delete)
                $this->products[$key]['href_delete'] = SEFLink('index.php?option=com_unocart&task=cart&task2=delete&number_id=' .
                    $key);
        }

    }
    function clear()
    {
        $this->products = array();
        $this->id = '';
        $this->rabatt = '';
        $this->rabatt_value = null;
        $this->rabatt_type = null;
        $this->rabatt_summ = null;
        $this->summ = 0;
        $this->count_product = 0;
        $_SESSION['cart'] = '';
        $_SESSION['pm_method'] = '';
        $_SESSION['pm_params'] = '';
        $_SESSION['payment_method_id'] = '';
        $_SESSION['shipping_method_id'] = '';
        $_SESSION['unocart_price_shipping'] = '';
    }

    function refreshCart($product_id, $quantity, $act_ajax, $attr_id)
    {
        if ($this->add($product_id, $quantity, $attr_id))
            $text = _UNOCART_ADDED_TO_CART;
        else
            $text = _UNOCART_ERROR_ADDED_TO_CART;
        $this->getSum();
        $params['price'] = $this->summ;
        if ($act_ajax) {
            header('Content-type: text/xml');
            echo '<?xml version = "1.0" encoding = "utf-8"?>';
            echo '<res><result text = "' . $text . '" quantity = "' . $this->count_product .
                '" summ = "' . html_entity_decode(format_price($params)) . '" /></res>';
        }
        return;
    }

    function addOrderItem($order_id)
    {
        foreach ($this->products as $key => $value) {
            $order_item = new unocartOrderItem($this->_db);
            $order_item->order_id = $order_id;
            $order_item->product_id = $value['product_id'];
            $order_item->product_ean = $value['ean'];
            $order_item->product_name = $value['product_name'];
            $order_item->product_quantity = $value['quantity'];
            $order_item->product_item_price = $value['price'];
            $order_item->product_tax = $value['tax'];
            $order_item->product_attributes = $attributes_value = '';
            if (isset($value['attributes_value'])) {
                //          	 if (is_object($value['attributes_value'])){
                foreach ($value['attributes_value'] as $attr) {
                    $attributes_value .= $attr->attr . ": " . $attr->value . "\n";
                }
                //             }
            }
            $order_item->product_attributes = $attributes_value;
            if (!$order_item->store()) {
                echo $order_item->getError();
                exit();
            }
            $arrProd[$key]['quantity'] = $value['quantity'];
            $arrProd[$key]['product_id'] = $value['product_id'];
        }

        // Vidnimaju tovary z nayavnosti
        unocartProduct::updateProductInStock($arrProd);
    }

    function delete($number_id)
    {
        unset($this->products[$number_id]);
        $this->saveToSession();
    }

    function saveToSession()
    {
        global $unocartConfig;
        $_SESSION['cart'] = $this;
    }

    function insertTempCart()
    {
        unocartTempCart::insertTempCart($this);
    }
}


class unocartTempCart
{
    function insertTempCart($cart)
    {
        $database = &unocartFactory::getDBO();
        $id_cookie = md5(uniqid(rand(), true));
        setcookie('unocart_temp_cart', $id_cookie, time() + 3600);
        $query = "INSERT INTO `#__unocart_cart_temp`
				  SET `id_cookie` = '" . $id_cookie . "',
					  `cart` = '" . serialize($cart->products) . "'";
        $database->setQuery($query);
        $database->query();
    }

    function getTempCart($id_cookie)
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT temp_cart.cart
				  FROM `#__unocart_cart_temp` AS temp_cart
				  WHERE temp_cart.id_cookie = '" . $id_cookie . "'
				  LIMIT 0,1";
        $database->setQuery($query);
        if ($temp_cart = $database->loadResult()) {
            $query = "DELETE FROM `#__unocart_cart_temp`
					  WHERE `id_cookie` = '" . $id_cookie . "'";
            $database->setQuery($query);
            $database->query();
            setcookie('unocart_temp_cart', $id_cookie, time() - 3600);
            return (unserialize($temp_cart));
        }
    }
}

class unocartWishList
{
    var $products = array();
    var $db;

    function unocartWishList()
    {
        global $my, $unocartConfig;
        $database = &unocartFactory::getDBO();
        $this->_db = $database;
        if (isset($_SESSION['wishlist'])) {
            $temp_wishlist = $_SESSION['wishlist'];
            $this->products = $temp_wishlist->products;
        } else {
            $this->products = array();
        }
        $this->remove_from_wishlist = $unocartConfig->remove_prod_f_wishlist;
    }

    function add($product_id)
    {
        if (!array_key_exists($product_id, $this->products)) {
            $product = new unocartProductExtend($this->_db);
            $product->load($product_id);
            $product->getDescriptionPrice();
            $product->getCategory();
            $this->products[$product_id]['category_id'] = $product->category_id;
            $this->products[$product_id]['name'] = $product->product_name;
            $this->products[$product_id]['description'] = $product->
                product_short_description;
            $this->products[$product_id]['product_name'] = $product->product_name;
            $this->products[$product_id]['thumb_image'] = $product->product_thumb_image;
            // This row for cycle in smarty
            $this->products[$product_id]['product_id'] = $product_id;
            // ------------------------------------------------------
        }
        $this->saveToSession();
        return 1;
    }

    function remove($product_id, $add_to_cart)
    {
        global $unocartConfig;
        if (array_key_exists($product_id, $this->products)) {
            if ($add_to_cart) {
                $cart = new Cart();
                $cart->add($product_id, 1);
                if ($this->remove_from_wishlist) {
                    unset($this->products[$product_id]);
                }
            } else {
                unset($this->products[$product_id]);
            }
        }
        $this->saveToSession();
    }

    function saveToSession()
    {
        global $unocartConfig;
        $_SESSION['wishlist'] = $this;
    }

    function addLinkToProducts()
    {
        foreach ($this->products as $key => $value) {
            $this->products[$key]['href'] = SEFLink('index.php?option=com_unocart&task=product&product_id=' .
                $key . '&category_id=' . $this->products[$key]['category_id']);
            $this->products[$key]['href_to_cart'] = SEFLink('index.php?option=com_unocart&task=remove_from_wishlist&cart=1&product_id=' .
                $key);
            $this->products[$key]['href_remove'] = SEFLink('index.php?option=com_unocart&task=remove_from_wishlist&product_id=' .
                $key);
        }
    }
}

class unocartUser extends mosDBTable
{
    var $user_id = null;
    var $usergroup_id;
    var $u_name = null;
    var $f_name = null;
    var $l_name = null;
    var $firma_name = null;
    var $email = null;
    var $street = null;
    var $zip = null;
    var $city = null;
    var $state = null;
    var $country = null;
    var $phone = null;
    var $fax = null;
    var $title = null;

    // Nide ne yuzaetsya - tilky dlya perevirky u funkcii check
    var $password = null;

    var $delivery_adress = null;
    var $d_f_name = null;
    var $d_l_name = null;
    var $d_firma_name = null;
    var $d_street = null;
    var $d_city = null;
    var $d_zip = null;
    var $d_state = null;
    var $d_phone = null;
    var $d_title = null;


    function unocartUser(&$database)
    {
        $database = &unocartFactory::getDBO();
        $this->mosDBTable('#__unocart_users', 'user_id', $database);
    }
    function isUserInShop($id)
    {
        $query = "SELECT users.user_id
				  FROM `#__unocart_users` AS users
				  WHERE users.user_id = '" . $id . "'";
        $this->_db->setQuery($query);
        $res = $this->_db->query();
        return $this->_db->getNumRows($res);
    }
    // Dodaju useriv, yakscho vin zareestrovanyj v joomla, ale ne v magazyni
    function addUserToTableShop($my)
    {
        $this->u_name = $my->username;
        $this->email = $my->email;
        $this->user_id = $my->id;
        // Vytyaguju pass, bo vin ne zberigaetsya v zminnij $my
        $query = "SELECT users.password
				  FROM `#__users` AS users
				  WHERE users.id = '" . $my->id . "'";
        $this->_db->setQuery($query);
        $password = $this->_db->loadResult();
        // Zapysuju rukamy, bo yakscho e zminna $user_id, to jde update
        $query = "INSERT INTO `#__unocart_users`
				  SET `u_name` = '" . $my->username . "', `email` = '" . $my->email .
            "', `user_id` = '" . $my->id . "', `password` = '" . $password . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
    }

    function check($checkout = 0)
    {
        global $mosConfig_uniquemail, $my;
        // Function for includes/joomla.php class mosUser Taras change
        if (Jstring::trim($this->f_name) == '') {
            $this->_error = addslashes(_UNOCART_REGWARN_NAME);
            return false;
        }

        if (Jstring::trim($this->l_name) == '') {
            $this->_error = addslashes(_UNOCART_REGWARN_LNAME);
            return false;
        }

        // check that username is not greater than 25 characters
        if ((Jstring::trim($this->email == "")) || (preg_match("/[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}/",
            $this->email) == false)) {
            $this->_error = addslashes(_UNOCART_REGWARN_MAIL);
            return false;
        }

        if (!$checkout) {
            if (Jstring::trim($this->u_name) == '') {
                $this->_error = addslashes(_UNOCART_REGWARN_UNAME);
                return false;
            }
            if (Jstring::strlen($this->u_name) > 25) {
                $this->u_name = Jstring::substr($this->u_name, 0, 25);
            }

            // check that password is not greater than 50 characters
            $password = $this->password;
            if (Jstring::strlen($password) > 50) {
                $this->password = Jstring::substr($password, 0, 50);
            }

            if (eregi("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]", $this->u_name) || Jstring::strlen($this->
                u_name) < 3) {
                $this->_error = sprintf(addslashes(_UNOCART_VALID_AZ09), addslashes(_UNOCART_USERNAME),
                    2);
                return false;
            }

            // check for existing username
            $query = "SELECT id" . "\n FROM #__users " . "\n WHERE username = " . $this->
                _db->Quote($this->u_name) . "\n AND id != " . (int)$this->user_id;
            $this->_db->setQuery($query);
            $xid = intval($this->_db->loadResult());
            if ($xid && $xid != intval($this->user_id)) {
                $this->_error = addslashes(_UNOCART_REGWARN_INUSE);
                return false;
            }

            if ($mosConfig_uniquemail) {
                // check for existing email
                $query = "SELECT id" . "\n FROM #__users " . "\n WHERE email = " . $this->_db->
                    Quote($this->email) . "\n AND id != " . (int)$this->user_id;
                $this->_db->setQuery($query);
                $xid = intval($this->_db->loadResult());
                if ($xid && $xid != intval($this->id)) {
                    $this->_error = addslashes(_UNOCART_REGWARN_EMAIL_INUSE);
                    return false;
                }
            }
        }

        // Taras add
        if (Jstring::trim($this->street) == '') {
            $this->_error = addslashes(_UNOCART_REGWARN_STREET);
            return false;
        }

        /*
        if ((preg_match("/^(\d){4,5}$/", $this->zip )==false)){
        $this->_error = addslashes( _UNOCART_REGWARN_ZIP );
        return false;
        }
        if (Jstring::trim($this->state) == ''){
        $this->_error = addslashes( _UNOCART_REGWARN_STATE );
        return false;
        }
        */
        if (!intval($this->country)) {
            $this->_error = addslashes(_UNOCART_REGWARN_COUNTRY);
            return false;
        }

        if (!intval($this->title)) {
            $this->_error = addslashes(_UNOCART_REGWARN_TITLE);
            return false;
        }

        /*
        if(Jstring::trim($this->phone) == '') {
        $this->_error = addslashes(_UNOCART_REGWARN_PHONE);
        return false;
        }
        */
        if ($checkout) {
            if ($this->delivery_adress) {
                if (Jstring::trim($this->d_f_name) == '') {
                    $this->_error = addslashes(_UNOCART_REGWARN_NAME_DELIVERY);
                    return false;
                }

                if (Jstring::trim($this->d_l_name) == '') {
                    $this->_error = addslashes(_UNOCART_REGWARN_LNAME_DELIVERY);
                    return false;
                }

                if (Jstring::trim($this->d_street) == '') {
                    $this->_error = addslashes(_UNOCART_REGWARN_STREET_DELIVERY);
                    return false;
                }

                /*		        if ((preg_match("/^(\d){4,5}$/", $this->d_zip )==false)){
                $this->_error = addslashes( _UNOCART_REGWARN_ZIP_DELIVERY );
                return false;
                }

                if (Jstring::trim($this->d_state) == ''){
                $this->_error = addslashes( _UNOCART_REGWARN_STATE_DELIVERY );
                return false;
                }
                */
                if (!intval($this->d_title)) {
                    $this->_error = addslashes(_UNOCART_REGWARN_TITLE_DELIVERY);
                    return false;
                }

                /*
                if(Jstring::trim($this->d_phone) == '') {
                $this->_error = addslashes(_UNOCART_REGWARN_PHONE_DELIVERY);
                return false;
                }
                */

            }
        }
        // End Taras add
        return true;
    }

    function checkAccountData()
    {

    }
    // Static method
    function getAllUsers($limitstart, $limit)
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT *
				 FROM `#__unocart_users` AS users
				 INNER JOIN `#__users` AS users_main ON users.user_id = users_main.id
				 LIMIT " . $limitstart . ", " . $limit;
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        return $rows;
    }

    // Static method
    function getCountAllUsers()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT COUNT(users.user_id)
				 FROM `#__unocart_users` AS users
				 INNER JOIN `#__users` AS users_main ON users.user_id = users_main.id";
        $database->setQuery($query);
        return $database->loadResult();
    }

    // Static method
    function getCountryId($id_user)
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT country
				  FROM `#__unocart_users`
				  WHERE user_id = '" . $id_user . "'";
        $database->setQuery($query);
        return $database->loadResult();

    }

    // Static method
    function getDiscount($id_user)
    {
        if (!$id_user)
            return 0;
        $database = &unocartFactory::getDBO();
        $query = "SELECT usergroup.usergroup_discount/100
				  FROM `#__unocart_usergroups` AS usergroup
				  INNER JOIN `#__unocart_users` AS users ON users.usergroup_id = usergroup.usergroup_id
				  WHERE users.user_id = '" . $id_user . "'
				  LIMIT 0,1";
        $database->setQuery($query);
        return floatval($database->loadResult());
    }
}

class unocartUserGroup extends mosDBTable
{
    var $usergroup_id = null;
    var $usergroup_name = null;
    var $usergroup_discount = null;
    var $usergroup_description = null;
    var $usergroup_is_default = 0;

    function unocartUserGroup(&$database)
    {
        $this->mosDBTable('#__unocart_usergroups', 'usergroup_id', $database);
    }

    // Static
    function getAllUsergroups()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT *
				  FROM `#__unocart_usergroups`";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    //Static
    function resetDefaultUsergroup()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT `usergroup_id`
				  FROM `#__unocart_usergroups`
				  WHERE `usergroup_is_default`= '1'
				  LIMIT 0,1";
        $database->setQuery($query);
        $usergroup_default = $database->loadResult();
        $query = "UPDATE `#__unocart_usergroups`
				  SET `usergroup_is_default` = '0'";
        $database->setQuery($query);
        $database->query();
    }

    // Static
    function setDefaultUsergroup($usergroup_id)
    {
        $database = &unocartFactory::getDBO();
        $query = "UPDATE `#__unocart_usergroups`
				  SET `usergroup_is_default` = '1'
				  WHERE `usergroup_id`= '" . $usergroup_id . "'";
        $database->setQuery($query);
        $database->query();
    }

    // Static
    function getDefaultUsergroup()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT `usergroup_id`
				  FROM `#__unocart_usergroups`
				  WHERE `usergroup_is_default`= '1'
				  LIMIT 0,1";
        $database->setQuery($query);
        return $database->loadResult();
    }
}

class unocartManufacturer extends mosDBTable
{
    var $manufacturer_id = null;
    var $manufacturer_name = null;
    var $manufacturer_url = null;
    var $manufacturer_description = null;
    var $manufacturer_logo = null;
    var $manufacturer_publish = null;

    function unocartManufacturer(&$database)
    {
        $this->mosDBTable('#__unocart_manufacturers', 'manufacturer_id', $database);
    }

    // Static
    function getAllManufacturers($publish = 0)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("WHERE manuf.manufacturer_publish = '1'") : ("");
        $query = "SELECT manuf.*
				  FROM `#__unocart_manufacturers` AS manuf
				  $query_where
				  ORDER BY manuf.manufacturer_id";
        $database->setQuery($query);
        return $database->loadObjectList();
    }
    function getCountProducts()
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $query = "SELECT COUNT(pr.product_id)
				  FROM `#__unocart_products` AS pr
				  INNER JOIN `#__unocart_manufacturers` AS manuf ON manuf.manufacturer_id = pr.product_manufacturer_id
				  WHERE manuf.manufacturer_id = '" . $this->manufacturer_id .
            "' AND pr.product_publish = '1'";
        $database->setQuery($query);
        return $database->loadResult();
    }
    function getProducts($limitstart = null, $limit = null)
    {
        global $unocartConfig;
        if ($limit > 0) {
            $limit = " LIMIT " . $limitstart . " , " . $limit;
        }
        $query = "SELECT prod.product_id, prod.product_thumb_image, prod.product_publish, pr_cat.product_ordering, pr_cat.category_id, (prod.product_price*" .
            $unocartConfig->currency_value .
            ") AS product_price, IFNULL(cur_lang.product_name, def_lang.product_name) AS product_name, IFNULL(cur_lang.product_short_description, def_lang.product_short_description) AS product_short_description
				  FROM `#__unocart_products` AS prod
				  LEFT JOIN `#__unocart_products_to_categories` AS pr_cat ON pr_cat.product_id = prod.product_id
				  INNER JOIN `#__unocart_manufacturers` AS manuf ON manuf.manufacturer_id = prod.product_manufacturer_id
				  LEFT JOIN `#__unocart_products_description` AS cur_lang ON cur_lang.product_id = prod.product_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				  LEFT JOIN `#__unocart_products_description` AS def_lang ON def_lang.product_id = prod.product_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				  WHERE manuf.manufacturer_id = '" . $this->manufacturer_id . "'
				  GROUP BY prod.product_id
				  ORDER BY pr_cat.product_ordering ASC" . $limit;
        $this->_db->setQuery($query);
        $products = $this->_db->loadObjectList();
        return $products;
    }
}

class unocartCoupon extends mosDBTable
{
    var $coupon_id = null;
    var $coupon_code = null;
    var $coupon_type = null;
    var $coupon_value = null;
    var $coupon_start_date = null;
    var $coupon_expire_date = null;
    var $coupon_publish = null;
    function unocartCoupon(&$database)
    {
        $this->mosDBTable('#__unocart_coupons', 'coupon_id', $database);
    }

    // Static
    function getAllCoupons($publish = 1)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("WHERE coupons.coupon_publish = '1'") : ("");
        $query = "SELECT coupons.*
				  FROM `#__unocart_coupons` AS coupons
				  $query_where
				  ORDER BY coupons.coupon_id";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function existCoupon()
    {
        $query = "SELECT `coupon_id`
				  FROM `#__unocart_coupons`
				  WHERE `coupon_code` = '" . $this->coupon_code . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
        return $this->_db->getAffectedRows();
    }
}

class unocartRabatt
{
    var $error = null;
    var $code = null;
    var $coupon_type = null;
    var $coupon_value = null;

    function unocartRabatt(&$database)
    {
        $this->_db = $database;
    }

    function check()
    {
        global $unocartConfig;
        if (!$unocartConfig->use_rabatt_code) {
            $this->error = '<script type = "text/javascript">alert("' . html_entity_decode(_UNOCART_RABATT_NON_SUPPORT,
                ENT_QUOTES, $unocartConfig->charset) . '"); location.href = "' . SEFLink('index.php?option=com_unocart&task=cart') .
                '"</script>';
            return 0;
        }
        $date = mktime();
        $query = "SELECT coupon.coupon_value, coupon.coupon_type
				FROM `#__unocart_coupons` AS coupon
				WHERE coupon.coupon_code = '" . $this->_db->getEscaped($this->code) .
            "' AND coupon.coupon_publish = '1' AND ((UNIX_TIMESTAMP(coupon.coupon_expire_date) > " .
            $date . " AND UNIX_TIMESTAMP(coupon.coupon_start_date) < " . $date .
            ") OR (coupon.coupon_start_date = '0000-00-00' AND coupon.coupon_expire_date = '0000-00-00'))";
        $this->_db->setQuery($query);
        $this->_db->loadObject($row);
        if (!$row) {
            $this->error = '<script type = "text/javascript">alert("' . html_entity_decode(_UNOCART_RABATT_NON_CORRECT,
                ENT_QUOTES, $unocartConfig->charset) . '"); location.href = "' . SEFLink('index.php?option=com_unocart&task=cart') .
                '"</script>';
            return 0;
        } else {
            $this->coupon_type = $row->coupon_type;
            $this->coupon_value = $row->coupon_value;
            return 1;
        }
    }
}

class unocartPaymentMethod extends mosDBTable
{
    var $payment_id = null;
    var $payment_name = null;
    var $payment_code = null;
    var $payment_class = null;
    var $payment_publish = null;
    var $payment_ordering = null;
    var $payment_add_info = null;
    var $payment_description = null;
    var $payment_params = null;
    var $payment_type = null;

    function unocartPaymentMethod(&$database)
    {
        $this->mosDBTable('#__unocart_payment_method', 'payment_id', $database);
    }

    // Static
    function getAllPaymentMethods($publish = 1)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("WHERE payment.payment_publish = '1'") : ("");
        $query = "SELECT payment.*
				  FROM `#__unocart_payment_method` AS payment
				  $query_where
				  ORDER BY payment.payment_ordering";
        $database->setQuery($query);
        return $database->loadObjectList();
    }


    function getId()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT pm_method.payment_id
				  FROM `#__unocart_payment_method` AS pm_method
				  WHERE pm_method.payment_class = '" . $this->class . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }
}

class unocartShippingMethod extends mosDBTable
{
    var $shipping_id = null;
    var $shipping_name = null;
    var $shipping_publish = null;
    var $shipping_ordering = null;
    var $shipping_description = null;

    function unocartShippingMethod(&$database)
    {
        $this->mosDBTable('#__unocart_shipping_method', 'shipping_id', $database);
    }
    // Static method
    function getAllShippingMethods($publish = 1)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("WHERE shipping.shipping_publish = '1'") : ("");
        $query = "SELECT shipping.*
				  FROM `#__unocart_shipping_method` AS shipping
				  $query_where
				  ORDER BY shipping.shipping_ordering";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    // Static method
    function getAllShippingMethodsCountry($country_id, $publish = 1)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("AND sh_method.shipping_publish = '1'") : ("");
        $query = "SELECT *
				  FROM `#__unocart_shipping_method` AS sh_method
				  INNER JOIN `#__unocart_shipping_method_price` AS sh_pr_method ON sh_method.shipping_id = sh_pr_method.shipping_method_id
				  INNER JOIN `#__unocart_shipping_method_price_countries` AS sh_pr_method_country ON sh_pr_method_country.sh_pr_method_id = sh_pr_method.sh_pr_method_id
				  INNER JOIN `#__unocart_countries` AS countries  ON sh_pr_method_country.country_id = countries.country_id
				  WHERE countries.country_id = '" . $country_id . "' $query_where
                  ORDER BY sh_method.shipping_ordering";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function deletePrice($sh_pr_id)
    {
        $query = "DELETE
				  FROM `#__unocart_shipping_method_price`
				  WHERE `sh_pr_method_id` = '" . $sh_pr_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
    }
}


class unocartShippingMethodPrice extends mosDBTable
{
    var $sh_pr_method_id = null;
    var $shipping_method_id = null;
    var $shipping_stand_price = null;
    var $shipping_tax_id = null;

    function unocartShippingMethodPrice(&$database)
    {
        $this->mosDBTable('#__unocart_shipping_method_price', 'sh_pr_method_id', $database);
    }

    // Static method
    //TODO:treba pominyaty funkcijy zaleshno vid krain
    function getPricesWeight($sh_pr_method_id, $multiplier, $id_country)
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT (sh_pr_weight.shipping_price+sh_pr_weight.shipping_package_price*" .
            $multiplier . ") AS shipping_price, sh_pr_weight.shipping_weight_from, sh_pr_weight.shipping_weight_to
				  FROM `#__unocart_shipping_method_price` AS sh_price
				  INNER JOIN `#__unocart_shipping_method_price_weight` AS sh_pr_weight ON sh_pr_weight.sh_pr_method_id = sh_price.sh_pr_method_id
				  INNER JOIN `#__unocart_shipping_method_price_countries` AS sh_pr_countr ON sh_pr_weight.sh_pr_method_id = sh_pr_countr.sh_pr_method_id
				  WHERE sh_price.sh_pr_method_id = '" . $sh_pr_method_id .
            "'AND sh_pr_countr.country_id = '" . $id_country . "' 
				  ORDER BY sh_pr_weight.shipping_weight_from";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function getPrices()
    {
        $query = "SELECT *
				  FROM `#__unocart_shipping_method_price_weight` AS sh_price
				  WHERE sh_price.sh_pr_method_id = '" . $this->sh_pr_method_id . "'
				  ORDER BY sh_price.shipping_weight_from";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function getCountries()
    {
        $query = "SELECT sh_country.country_id, countries.country_name
				  FROM `#__unocart_shipping_method_price_countries` AS sh_country
				  INNER JOIN `#__unocart_countries` AS countries ON countries.country_id = sh_country.country_id
				  WHERE sh_country.sh_pr_method_id = '" . $this->sh_pr_method_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }


    // Static method
    function getAllShippingMethodsPrices($publish = 1)
    {
        $database = &unocartFactory::getDBO();
        $query_where = ($publish) ? ("WHERE shipping.shipping_publish = '1'") : ("");
        $query = "SELECT shipping_price.*, shipping.shipping_name
				  FROM `#__unocart_shipping_method_price` AS shipping_price
				  INNER JOIN `#__unocart_shipping_method` AS shipping ON shipping.shipping_id = shipping_price.shipping_method_id
				  $query_where
				  ORDER BY shipping_price.sh_pr_method_id";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function saveCountries($countries)
    {
        $query = "DELETE FROM `#__unocart_shipping_method_price_countries` WHERE `sh_pr_method_id` = '" .
            $this->sh_pr_method_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
        foreach ($countries as $key => $value) {
            $query = "INSERT INTO `#__unocart_shipping_method_price_countries`
					  SET `country_id` = '" . $value . "', `sh_pr_method_id` = '" . $this->
                sh_pr_method_id . "'";
            $this->_db->setQuery($query);
            if (!$this->_db->query()) {
                echo $this->_db->stderr();
                die();
            }
        }
    }

    function savePrices($array_post)
    {
        foreach ($array_post['shipping_price'] as $key => $value) {
            if (isset($array_post['delete_sh_pr'][$key])) {
                $this->deletePriceWeight($key);
                continue;
            }
            $sh_method = new unocartShippingMethodPriceWeight($this->_db);
            $sh_method->sh_pr_weight_id = (isset($array_post['old_sh_pr'][$key])) ? ($key) : ('');
            $sh_method->sh_pr_method_id = $this->sh_pr_method_id;
            $sh_method->shipping_price = $array_post['shipping_price'][$key];
            $sh_method->shipping_package_price = $array_post['shipping_package_price'][$key];
            $sh_method->shipping_weight_from = $array_post['shipping_weight_from'][$key];
            $sh_method->shipping_weight_to = $array_post['shipping_weight_to'][$key];
            if (!$sh_method->store()) {
                trigger_error("error saving to database" . $sh_method->_db->stderr(),
                    E_USER_ERROR);
            }
        }
    }

    function deletePriceWeight($sh_pr_weight_id)
    {
        $query = "DELETE
				  FROM `#__unocart_shipping_method_price_weight`
				  WHERE `sh_pr_weight_id` = '" . $sh_pr_weight_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
    }


    function getTax()
    {
        $query = "SELECT tax.tax_value
				  FROM `#__unocart_shipping_method_price` AS sh_method_price
				  INNER JOIN `#__unocart_taxes` AS tax ON tax.tax_id = sh_method_price.shipping_tax_id
				  WHERE sh_method_price.sh_pr_method_id = '" . $this->sh_pr_method_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }

    function calculateSum($multiplier, &$cart)
    {
        global $unocartConfig;
        if ($cart->getSum() >= $unocartConfig->summ_null_shipping && $unocartConfig->
            summ_null_shipping > 0)
            return 0;
        $weight_sum = $cart->getWeightProducts();
        $sh_price = $this->getPrices();
        foreach ($sh_price as $sh_pr) {
            if ($weight_sum > $sh_pr->shipping_weight_from && $weight_sum < $sh_pr->
                shipping_weight_to) {
                return $sh_pr->shipping_price + $sh_pr->shipping_package_price;
            }
        }
        return $this->shipping_stand_price;
    }

    function calculateTax($sum)
    {
        return $sum - $sum / (1 + $this->getTax() / 100);

    }

    // Check, chy mozhlyvyi cei method oplaty dlya krainy pokupcya
    function isCorrectMethodForCountry($id_country)
    {
        $query = "SELECT `sh_method_country_id` 
				  FROM `#__unocart_shipping_method_price_countries`
				  WHERE `country_id` = '" . $id_country . "' AND `sh_pr_method_id` = '" . $this->
            sh_pr_method_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
        return ($this->_db->getNumRows()) ? (1) : (0);
    }

}

class unocartShippingMethodPriceWeight extends mosDBTable
{
    var $sh_pr_weight_id = null;
    var $sh_pr_method_id = null;
    var $shipping_price = null;
    var $shipping_package_price = null;
    var $shipping_weight_to = null;
    var $shipping_weight_fron = null;
    function unocartShippingMethodPriceWeight(&$database)
    {
        $this->mosDBTable('#__unocart_shipping_method_price_weight', 'sh_pr_weight_id',
            $database);
    }
}

class unocartOrder extends mosDBTable
{
    var $order_id = null;
    var $order_number = null;
    var $user_id = null;
    var $order_total = null;
    var $order_subtotal = null;
    var $order_tax = null;
    var $order_shipping = null;
    var $order_discount = null;
    var $currency_code = null;
    var $order_status = null;
    var $order_date = null;
    var $order_m_date = null;
    var $shipping_method_id = null;
    var $payment_method_id = null;
    var $payment_params = null;
    var $ip_address = null;
    var $order_add_info = null;
    var $f_name = null;
    var $l_name = null;
    var $firma_name = null;
    var $email = null;
    var $street = null;
    var $zip = null;
    var $city = null;
    var $state = null;
    var $country = null;
    var $phone = null;
    var $fax = null;
    var $title = null;
    var $delivery_adress = null;
    var $d_f_name = null;
    var $d_l_name = null;
    var $d_firma_name = null;
    var $d_street = null;
    var $d_zip = null;
    var $d_city = null;
    var $d_state = null;
    var $d_phone = null;
    var $d_title = null;
    var $pdf_file = null;
    var $order_hash = null;
    var $order_custom_info = null;

    function unocartOrder(&$database)
    {
        $this->mosDBTable('#__unocart_orders', 'order_id', $database);
    }

    // Work with assoc list
    function calcNettoPrice()
    {
        foreach ($this->products as $key => $value) {
            $this->products[$key]['price_netto'] = round($value['price'] / (1 + $value['tax'] /
                100), 2);
        }
    }
    // Work with Object
    // Ranishe cjogo bulo ne potribno, ale Klaus zahotiv zminyty format vyvode zamovlennya, tomu-to taka fignya vyishla
    function calcNettoPriceObject()
    {
        foreach ($this->products as $key => $value) {
            $this->products[$key]->price_netto = round($value->product_item_price / (1 + $value->
                product_tax / 100), 2);
        }
    }

    function calcSumNetto()
    {
        $summ = 0;
        foreach ($this->products as $key => $value) {
            $summ += $value->price_netto * $value->product_quantity;
        }
        return round($summ, 2);
    }


    function getAllItems()
    {
        $query = "SELECT *
				  FROM `#__unocart_order_item` AS order_item
				  WHERE order_item.order_id = '" . $this->order_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function getHistory()
    {
        $query = "SELECT history.*, status.*
				  FROM `#__unocart_order_history` AS history
				  INNER JOIN `#__unocart_order_status` AS status ON history.order_status_id = status.status_id
				  WHERE history.order_id = '" . $this->order_id . "'
				  ORDER BY history.status_date_added";
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }

    function getStatus()
    {
        $query = "SELECT status.status_name
				  FROM `#__unocart_order_status` AS status
				  WHERE status.status_id = '" . $this->order_status . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }
    // Static
    function getCountAllOrders($status_id = null)
    {
        $database = &unocartFactory::getDBO();
        $where = ($status_id) ? ("WHERE orders.order_status = '" . $status_id . "'") :
            "";
        $query = "SELECT COUNT(orders.order_id)
				  FROM `#__unocart_orders` AS orders " . $where;
        $database->setQuery($query);
        return $database->loadResult();
    }

    // Static
    function getAllOrders($limitstart, $limit, $status_id = null)
    {
        $database = &unocartFactory::getDBO();
        $where = ($status_id) ? ("WHERE orders.order_status = '" . $status_id . "'") :
            "";
        $query = "SELECT orders.*
				  FROM `#__unocart_orders` AS orders
				  $where
				  ORDER BY orders.order_id DESC
				  LIMIT $limitstart, $limit";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function checkDeliveryData()
    {
        if (!$this->delivery_adress) {
            $this->d_title = $this->title;
            $this->d_f_name = $this->f_name;
            $this->d_l_name = $this->l_name;
            $this->d_firma_name = $this->firma_name;
            $this->d_street = $this->street;
            $this->d_zip = $this->zip;
            $this->d_city = $this->city;
            $this->d_state = $this->state;
            $this->d_phone = $this->phone;
        }
    }

    function getOrdersForUser($id_user)
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT orders.*, order_status.status_name, COUNT(order_item.order_id) AS count_products
				  FROM `#__unocart_orders` AS orders
				  INNER JOIN `#__unocart_order_status` AS order_status ON orders.order_status = order_status.status_id
				  INNER JOIN `#__unocart_order_item` AS order_item ON order_item.order_id = orders.order_id
				  WHERE orders.user_id = '" . $id_user . "'
				  GROUP BY order_item.order_id
				  ORDER BY orders.order_date DESC";
        $database->setQuery($query);
        return $rows = $database->loadObjectList();
    }

    // static function
    function getLastOrderId()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT MAX(orders.order_id) AS max_order_id
				  FROM `#__unocart_orders` AS orders";
        $database->setQuery($query);
        return $database->loadResult() + 1;
    }

    // Function, yaka obnovlyae zapysy u bazi pro pdf_file orderu
    function insertPDF()
    {
        $query = "UPDATE `#__unocart_orders` AS orders
				  SET orders.pdf_file = '" . $this->pdf_file . "'
				  WHERE orders.order_id = '" . $this->order_id . "'";
        $this->_db->setQuery($query);
        $this->_db->query();
    }
}

class unocartOrderStatus extends mosDBTable
{
    var $status_id = null;
    var $status_name = null;
    var $status_code = null;
    function unocartOrderStatus(&$database)
    {
        $this->mosDBTable('#__unocart_order_status', 'status_id', $database);
    }

    // Static
    function getAllOrders()
    {
        $database = &unocartFactory::getDBO();
        $query = "SELECT status.*
				  FROM `#__unocart_order_status` AS status
				  ORDER BY status.status_id";
        $database->setQuery($query);
        return $database->loadObjectList();
    }

    function getName($status_id)
    {
        $query = "SELECT status.status_name
				  FROM `#__unocart_order_status` AS status
				  WHERE status.status_id = '" . $status_id . "'";
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }
}

class unocartOrderItem extends mosDBTable
{
    var $order_item_id = null;
    var $order_id = null;
    var $product_id = null;
    var $product_ean = null;
    var $product_name = null;
    var $product_quantity = null;
    var $product_item_price = null;
    var $product_tax = null;
    var $product_attributes = null;

    function unocartOrderItem(&$database)
    {
        $this->mosDBTable('#__unocart_order_item', 'order_item_id', $database);
    }
}

class unocartOrderHistory extends mosDBTable
{
    var $order_history_id = null;
    var $order_id = null;
    var $order_status_id = null;
    var $status_date_added = null;
    var $customer_notify = null;
    var $comments = null;

    function unocartOrderHistory(&$database)
    {
        $this->mosDBTable('#__unocart_order_history', 'order_history_id', $database);
    }

}

class unocartAttribut
{
    function unocartAttribut(&$database)
    {
        $this->_db = $database;
    }

    function getName($attr_id)
    {
        global $unocartConfig;
        $query = "SELECT DISTINCT attr.attr_id, IFNULL(cur_lang.attr_name, def_lang.attr_name) AS attr_name
				FROM `#__unocart_attr` AS attr
				LEFT JOIN `#__unocart_attr` AS cur_lang ON cur_lang.attr_id = attr.attr_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "' 
				LEFT JOIN `#__unocart_attr` AS def_lang ON def_lang.attr_id = attr.attr_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "' 
				WHERE attr.attr_id = '" . $attr_id . "'";
        $this->_db->setQuery($query);
        $all_attr = $this->_db->loadObject($attribut);
        return $attribut->attr_name;
    }
    // Static
    function getAllAttributes()
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $query = "SELECT attr.attr_id, IFNULL(cur_lang.attr_name, def_lang.attr_name) AS attr_name, attr.attr_ordering
				FROM `#__unocart_attr` AS attr
				LEFT JOIN `#__unocart_attr` AS cur_lang ON cur_lang.attr_id = attr.attr_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "' 
				LEFT JOIN `#__unocart_attr` AS def_lang ON def_lang.attr_id = attr.attr_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "' 
				GROUP BY attr.attr_id
				ORDER BY attr.attr_ordering";
        $database->setQuery($query);
        $attribs = $database->loadObjectList();
        return $attribs;
    }
}


class unocartValue
{
    function unocartValue(&$database)
    {
        $this->_db = $database;
    }

    function getName($value_id)
    {
        global $unocartConfig;
        $query = "SELECT DISTINCT valu.value_id, IFNULL(cur_lang.value_name, def_lang.value_name) AS value_name
				FROM `#__unocart_attr_values` AS valu
				LEFT JOIN `#__unocart_attr_values` AS cur_lang ON cur_lang.value_id = valu.value_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				LEFT JOIN `#__unocart_attr_values` AS def_lang ON def_lang.value_id = valu.value_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				WHERE valu.value_id = '" . $value_id . "'";
        $this->_db->setQuery($query);
        $this->_db->loadObject($value);
        return $value->value_name;
    }

    // Static
    function getAllValues($attr_id)
    {
        global $unocartConfig;
        $database = &unocartFactory::getDBO();
        $query = "SELECT DISTINCT valu.value_id, valu.image, IFNULL(cur_lang.value_name, def_lang.value_name) AS value_name, attr_valu.value_id_to_attr_id, valu.value_ordering, valu.language
				FROM `#__unocart_attr_to_values` AS attr_valu
				INNER JOIN `#__unocart_attr_values` AS valu ON valu.value_id = attr_valu.value_id
				INNER JOIN `#__unocart_attr` AS attr ON attr_valu.attr_id = attr.attr_id 
				LEFT JOIN `#__unocart_attr_values` AS cur_lang ON cur_lang.value_id = valu.value_id AND cur_lang.language = '" .
            $unocartConfig->cur_lang . "'
				LEFT JOIN `#__unocart_attr_values` AS def_lang ON def_lang.value_id = valu.value_id AND def_lang.language = '" .
            $unocartConfig->defaultLanguage . "'
				WHERE attr.attr_id = '" . $attr_id . "'
				GROUP BY valu.value_id
				ORDER BY valu.value_ordering, valu.value_id";
        $database->setQuery($query);
        return $values = $database->loadObjectList();
    }
}

class unocartReview extends mosDBTable
{
    var $review_id = null;
    var $product_id = null;
    var $user_id = null;
    var $user_name = null;
    var $user_email = null;
    var $time = null;
    var $review = null;
    var $mark = null;

    function unocartReview(&$database)
    {
        $this->mosDBTable('#__unocart_products_reviews', 'review_id', $database);
    }

    // Static method
    // $type = null - product
    // $type = other - manufacturer
    function getAllowReview($type = null)
    {
        global $my, $unocartConfig;
        if ($type) {
            if (!$unocartConfig->allow_reviews_manuf) {
                return 0;
            }
        } else {
            if (!$unocartConfig->allow_reviews_prod) {
                return 0;
            }
        }
        if ($unocartConfig->allow_reviews_only_registered && !$my->id) {
            return - 1;
        }
        return 1;
    }

    function getText()
    {
        global $unocartConfig;
        // Not logged in
        if (unocartReview::getAllowReview() == -1) {
            return _UNOCART_REVIEW_NOT_LOGGED;
        } else {
            return '';
        }
    }

}

class unocartPriceRequest extends mosDBTable
{
    var $request_id = null;
    var $product_id = null;
    var $user_id = null;
    var $request_message = null;
    var $status = null;
    var $request_date = null;
    function unocartPriceRequest(&$database)
    {
        $this->mosDBTable('#__unocart_prices_requests', 'request_id', $database);
    }
}

class unocartFactory
{
    function &getDBO()
    {
        global $unocartConfig;
        static $instance;
        static $config;
        if (!is_object($config)) {
            $config = new stdClass();
        }
        if (!is_object($instance)) {
            global $database;
            $instance = $database;
        }
        return $instance;
    }
}

?>